/*
 * @copyright 2010 Gerald Jacobson
 * @license GNU General Public License
 * 
 * This file is part of My Quick Rules.
 *
 * My Quick Rules is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * My Quick Rules is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with My Quick Rules.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.amphiprion.myquickrules.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.amphiprion.myquickrules.Home;
import org.amphiprion.myquickrules.entity.Game;
import org.amphiprion.myquickrules.entity.LocalGame;
import org.amphiprion.myquickrules.util.ApplicationConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.os.Environment;
import android.util.Log;

/**
 * @author Amphiprion
 * 
 */
public class GameDao extends AbstractDao {
	private static GameDao instance;

	public static GameDao getInstance() {
		if (instance == null) {
			instance = new GameDao();
		}
		return instance;
	}

	public List<Game> getAvailableGames(String sUrl) {
		ArrayList<Game> games = new ArrayList<Game>();
		String lng = Locale.getDefault().getLanguage();
		try {
			URL url = new URL(sUrl);
			URLConnection c = url.openConnection();
			InputStream is = c.getInputStream();

			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			builderFactory.setNamespaceAware(true);

			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(is);
			NodeList list = document.getElementsByTagName("game");
			for (int i = 0; i < list.getLength(); i++) {
				Element gameNode = (Element) list.item(i);
				String id = gameNode.getAttributes().getNamedItem("id").getNodeValue();

				// NAME
				String name = "";
				NodeList langs = gameNode.getElementsByTagName("lang");
				for (int iNames = 0; iNames < langs.getLength(); iNames++) {
					try {
						Element lang = (Element) langs.item(iNames);
						String local = getAttribute(lang, "id", "en");
						if (local.equals(lng)) {
							name = langs.item(iNames).getFirstChild().getNodeValue();
							break;
						} else if ("en".equals(local)) {
							name = langs.item(iNames).getFirstChild().getNodeValue();
						}
					} catch (NullPointerException npe) {
					}
				}

				Game game = new Game();
				game.setId(id);
				game.setName(name);
				games.add(game);
			}
		} catch (Exception e) {
			Log.e(ApplicationConstants.PACKAGE, "getAvailableGames(String sUrl)", e);
		}
		return games;
	}

	public List<LocalGame> getGames(String query) {
		ArrayList<LocalGame> games = new ArrayList<LocalGame>();
		String regexp = null;
		if ((query!=null) && (query.length()>0)) {
			regexp = "(?i).*" + query + ".*";
		}
		String lng = Locale.getDefault().getLanguage();
		try {
			File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/games.xml");

			InputStream is = null;
			if (f.exists()) {
				is = new FileInputStream(f);
			}
			if (is == null) {
//				is = Home.class.getResourceAsStream("/games.xml");
				return null;
			}

			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			builderFactory.setNamespaceAware(true);

			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(is);

			NodeList list = document.getElementsByTagName("game");
			for (int i = 0; i < list.getLength(); ++i) {
				Element gameNode = (Element) list.item(i);
				String id = gameNode.getAttributes().getNamedItem("id").getNodeValue();
				String version = gameNode.getAttributes().getNamedItem("version").getNodeValue();
				String resolution = gameNode.getAttributes().getNamedItem("resolution").getNodeValue();
				String creator = getAttribute(gameNode, "creator", "Amphiprion");
				String mail = getAttribute(gameNode, "mail", "amphiprions@gmail.com");

				// NAME
				String name = "";
				NodeList langs = gameNode.getElementsByTagName("lang");
				for (int iNames = 0; iNames < langs.getLength(); iNames++) {
					try {
						Element lang = (Element) langs.item(iNames);
						String local = getAttribute(lang, "id", "en");
						if (local.equals(lng)) {
							name = langs.item(iNames).getFirstChild().getNodeValue();
							break;
						} else if ("en".equals(local)) {
							name = langs.item(iNames).getFirstChild().getNodeValue();
						}
					} catch (NullPointerException npe) {
					}
				}
				
				// check filter
				if (regexp!=null) {
					if (!name.matches(regexp)) {
						// not acceptable for this filter
						continue;
					}
				}

				// ok add it
				LocalGame game = new LocalGame();
				game.setId(id);
				game.setName(name);
				game.version = version;
				game.resolution = resolution;
				game.creator = creator;
				game.mail = mail;
				games.add(game);
			}
			is.close();
			return games;
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			return null;
		}

	}

}
